const call = require('../../utils/request.js');
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    quesType: 2, //1视频 2图文
    balance: 0, //健康币
    deduct: false, //是否抵扣
    payType: 'MINI_WECHAT', //支付方式 微信WECHAT 支付宝ALIPAY /小程序 MINI_WECHAT
    price:'', //价格
  },

  onLoad: function (options) {
    let price = 30; //视频价格
    if(options.type == 2) price = 2; //图文价格

    this.setData({
      price:price,
      quesType:options.type,  //1视频 2图文 3预约
    })

    //判断健康币是否足够
    this.initData();
    // var balance = uni.getStorageSync("balance"); 
    // console.log("当前健康币",balance)
    // if (balance == "") balance = 0; 
    // this.balance = parseFloat(balance);
  },

  onReady: function () {

  },

  onShow: function () {

  },

  onHide: function () {
    
  },

  //获取页面基本数据信息
  initData(){
    wx.showLoading({
      title: '正在获取数据',
      mask:true
    })
    call.get('/api/home/index').then(res=>{
      console.log("获取健康币",res.data.data.balance)
      wx.hideLoading();
      if(res.data.code == 0){
        this.setData({
          balance: parseFloat(res.data.data.balance)
        })
      }
    })
  },

  //选择抵扣
  changeDeduct() {
    //健康币低于抵扣值不允许选择抵扣
    if (this.data.balance < (this.data.price*100)) { return; } 
    this.setData({
      deduct: (!this.data.deduct)
    })
  }, 
  
  //选择支付方式
  chooseType(e) { 
    this.setData({
      payType: e.currentTarget.dataset.type
    })
  }, 

  // 上传图片
  uploadImg() {
    if (this.data.quesType == 1 || this.data.quesType == 3) { //视频问诊
      this.submitOrder('');
    } else {  //图文问诊
      var obj = JSON.parse(wx.getStorageSync('question')); 
      if (obj.imgArr.length > 0) { 
        wx.showLoading({
          title: '正在上传图片',
          mask:true
        })
        call.post('/api/upload/base64_img', { file: obj.imgArr.join('|') }).then((res)=> { 
          wx.hideLoading();
          console.log("上传图片", res.data.data); 
          if (res.statusCode == 200 && res.data.code == 0) { 
            this.submitOrder(res.data.data); 
          } 
        }); 
      } else { 
        this.submitOrder(''); 
      }
    }
  }, 

  //提交问题 1视频 2图文 3预约
  submitOrder(arr) {
    const quesType = this.data.quesType;
    const deduct = this.data.deduct;
    //请求地址
    var url = '/api/graphic/questions'; 
    if (quesType == 1) url = '/api/camera/generate_order'; //请求的数据
    if(quesType == 3) url = '/api/camera/appointment';
    var data = {}; 
    if (quesType == 1) {
      data = {
        doctor_id:app.globalData.doctorId,
        pay_type: deduct ? 'coin' : 'money',
        payment_source: 'MINI_WECHAT'
      };
    } else if(quesType == 2) {
      var obj = JSON.parse(wx.getStorageSync('question'));
      data = {
        doctor_id: obj.id,
        content: obj.content,
        type: deduct ? 2 : 1, //支付形式（1金额 2健康币）
        image_source: arr,
        payment_source: 'MINI_WECHAT', //this.payType, //支付类型 （MINI_WECHAT 微信小程序，WECHAT 微信支付，ALIPAY 支付宝支付）
        amount: deduct ? this.data.price*100 : this.data.price //金额
      };
    }else if(quesType == 3){
      console.log(wx.getStorageSync('yyTime'))
      const obj = JSON.parse(wx.getStorageSync('yyTime'));
      data = {
        doctor_id: obj.id,
        start_time: obj.start_time,
        end_time: obj.end_time,
        pay_type: deduct ? 'coin' : 'money',
        payment_source: 'MINI_WECHAT'
      }
    }

    wx.showLoading({
      title: '正在提交',
      mask:true
    })
    call.post(url, data).then((res1) => {
      wx.hideLoading();
      console.log("发起提问", res1);
      if (res1.statusCode == 200 && res1.data.code == 0) {
        var _data = res1.data.data;
        if (deduct) {
          wx.showLoading({
            title: '正在跳转',
            mask: true
          });
          setTimeout(() => {
            wx.reLaunch({
              url: "../success/success?type=".concat(quesType, "&order=").concat(_data.order)
            });
          }, 2000);
        } else {
          wx.requestPayment({
            timeStamp: res1.data.data.timeStamp,
            nonceStr: res1.data.data.nonceStr,
            package: res1.data.data.package,
            signType: res1.data.data.signType,
            paySign: res1.data.data.paySign,
            success: (res) => {
              console.log("调用成功");
              wx.showLoading({
                title: '正在跳转',
                mask: true
              });
              setTimeout(() => {
                wx.reLaunch({
                  url: "../success/success?type=".concat(quesType, "&order=").concat(_data.order)
                });
              }, 2000);
            },
            fail: function fail(res) {
              console.log("调用失败");
              wx.reLaunch({
                url: '../index/index'
              });

            }
          });
        }
      }
    });
  }
})